package com.ruoyi.web.controller.common;


import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.system.service.ISysConfigService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController("UserPhotoController")
@RequestMapping("/user/photo")
public class PhotoController extends BaseController {

    @Resource
    private ISysConfigService sysConfigService;


    /**
     * 返回用户照片
     *
     * @throws IOException
     */
    @GetMapping()
    public AjaxResult photo() throws IOException {
        LoginUser loginUser = getLoginUser();
        String basePath = sysConfigService.selectConfigByKey("student-photo-local-path");
        String imageFilePath = basePath + loginUser.getUsername() + ".jpg";
        File file = new File(imageFilePath);
        if (!file.exists()) {
            //如果学生头像不存在，那么修改为默认图片
            imageFilePath = basePath + "no_image2.png";
            file = new File(imageFilePath);
            if (!file.exists()) {
                //如果默认还不存在，直接返回空
                return success();
            }
        }
        FileInputStream fileInputStream = new FileInputStream(file);
        //使用IO流将其转换为字节数组
        byte[] bytes = IOUtils.toByteArray(fileInputStream);
        //将字节转换为base64
        String encodeBase64 = Base64.encodeBase64String(bytes);
        //关闭IO流
        fileInputStream.close();
        return success(encodeBase64);
    }
}
